package com.kpmg.datalake.vbaapi.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageInfo;
import com.kpmg.datalake.accountcheck.service.AccountCheckService;
import com.kpmg.datalake.accountcheck.vo.AccountQueryVO;
import com.kpmg.datalake.common.dynamicdatasource.DynamicDS;
import com.kpmg.datalake.common.enums.ReportTypeEnum;
import com.kpmg.datalake.common.enums.ResultCodeEnum;
import com.kpmg.datalake.common.enums.SysOptionCodeEnum;
import com.kpmg.datalake.common.enums.VbaOptionType;
import com.kpmg.datalake.common.model.DateInfo;
import com.kpmg.datalake.common.model.DimInfo;
import com.kpmg.datalake.common.model.OptionDataModel;
import com.kpmg.datalake.common.model.ReportCondition;
import com.kpmg.datalake.common.model.ReportDate;
import com.kpmg.datalake.common.service.BaseInfoService;
import com.kpmg.datalake.common.service.CommonExecuteService;
import com.kpmg.datalake.common.service.IProjectRptSqlService;
import com.kpmg.datalake.common.utils.AssertUtil;
import com.kpmg.datalake.common.utils.ContextHolderUtils;
import com.kpmg.datalake.common.utils.ExceptionUtil;
import com.kpmg.datalake.common.vo.KeyAndValueDTO;
import com.kpmg.datalake.common.vo.ServerResponse;
import com.kpmg.datalake.db.dao.SysUsrOptionMapper;
import com.kpmg.datalake.db.model.SysOption;
import com.kpmg.datalake.db.model.SysUsr;
import com.kpmg.datalake.db.model.SysUsrOption;
import com.kpmg.datalake.reportanalysis.dao.ReportMapper;
import com.kpmg.datalake.reportanalysis.service.ReportService;
import com.kpmg.datalake.vbaapi.service.ISysOptionService;
import com.kpmg.datalake.vbaapi.service.VbaVisualService;
import com.kpmg.datalake.vbaapi.vo.VbaParamsDTO;
import com.kpmg.datalake.vbaapi.vo.VbaReportOptionVO;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * VBA可视化后端功能Service
 *
 * @author timqian
 * @author alex [alex.zhao@kpmg.com]
 */
@Service
public class VbaVisualServiceImpl implements VbaVisualService {

  private static final Logger logger = LoggerFactory.getLogger(VbaVisualServiceImpl.class);

  private static final String UNDERLINE_SEPARATOR = "_";

  public static final String OPTION_CODE = "code";

  public static final String OPTION_VALUE = "value";

  public static final String OPTION_LEVEL = "level";

  public static final String OPTION_KEY = "key";

  public static final int DEFAULT_OPTION_LEVEL = 1;

  public static final String START_DATE_KEY = "startDate";

  public static final String END_DATE_KEY = "endDate";


  public static final String ACG_YEAR_KEY = "acgYr";

  public static final String ACG_MONTH_KEY = "acgMo";

  /**
   * 客户代码
   */
  public static final String CORP_CODE = "coprCd";
  /**
   * 客户名称
   */
  public static final String CORP_NAME = "coprNm";
  /**
   * 交易对手代码
   */
  public static final String CST_CODE = "cstCd";
  /**
   * 部门代码
   */
  public static final String DEPT_CODE = "deptCd";
  /**
   * 组团代码
   */
  public static final String PRJ_CODE = "prjCd";

  /**
   * VBA 报告行数限制
   */
  private static final int VBA_REPORT_FETCH_LIMITATION = 10000;


  @Resource
  private SysUsrOptionMapper sysUsrOptionMapper;


  @Resource
  private CommonExecuteService commonExecuteService;

  @Resource
  private AccountCheckService accountCheckService;

  @Resource
  private BaseInfoService baseInfoService;

  @Resource
  private ReportService reportService;

  @Resource
  private ISysOptionService sysOptionService;

  @Autowired
  private ReportMapper reportMapper;
  @Resource
  private IProjectRptSqlService projectRptSqlService;


  @Override
  public ServerResponse<VbaReportOptionVO<DimInfo>> initCorp(VbaParamsDTO vbaParamsDTO) {
    VbaReportOptionVO<DimInfo> corpOptionVO;
    try {
      AssertUtil.assertNotEmpty(vbaParamsDTO.getProjectId(), ResultCodeEnum.CODE4005.getDisplay());
      PageInfo<DimInfo> pageInfo =
          baseInfoService.initCorp(-1, -1, vbaParamsDTO.getProjectId(), vbaParamsDTO.getParam());
      List<DimInfo> dimInfoList = pageInfo.getList();
      corpOptionVO = new VbaReportOptionVO<>("defaultReportCorp", "默认报告客户下拉框选项", "客户",
          VbaOptionType.COMBO_BOX.getCode());
      if (!ObjectUtils.isEmpty(dimInfoList)) {
        corpOptionVO.setDefaultValue(dimInfoList.get(0).getCode());
        corpOptionVO.setOptionDictionaryList(dimInfoList);
      }
    } catch (Exception e) {
      logger.error(e.getMessage());
      return ExceptionUtil.getExceptionMsg(e);
    }

    return ServerResponse.createBySuccess(corpOptionVO);
  }

  @Override
  public ServerResponse<ArrayList<VbaReportOptionVO<JSONObject>>> initReportDate(
      VbaParamsDTO vbaParamsDTO) {

    ArrayList<VbaReportOptionVO<JSONObject>> resultList;
    try {
      AssertUtil.assertNotEmpty(vbaParamsDTO.getProjectId(), ResultCodeEnum.CODE4005.getDisplay());
      List<ReportDate> dataList = baseInfoService.initDate(vbaParamsDTO.getProjectId());
      VbaReportOptionVO<JSONObject> startDateOptionVO = new VbaReportOptionVO<>(
          "defaultReportStartDate", "默认报表开始日期下拉框选项", "开始日期", VbaOptionType.COMBO_BOX.getCode());
      VbaReportOptionVO<JSONObject> endDateOptionVO = new VbaReportOptionVO<>(
          "defaultReportEndDate", "默认报表结束日期下拉框选项", "结束日期", VbaOptionType.COMBO_BOX.getCode());
      if (!dataList.isEmpty()) {
        Map<String, List<JSONObject>> reportDateMap = convertReportDates(dataList);
        List<JSONObject> startDateList = reportDateMap.get(START_DATE_KEY);
        List<JSONObject> endDateList = reportDateMap.get(END_DATE_KEY);
        startDateOptionVO.setOptionDictionaryList(startDateList);
        endDateOptionVO.setOptionDictionaryList(endDateList);
        if (!startDateList.isEmpty()) {
          startDateOptionVO.setDefaultValue(startDateList.get(0).getString(OPTION_CODE));
        }
        if (!endDateList.isEmpty()) {
          endDateOptionVO.setDefaultValue(endDateList.get(0).getString(OPTION_CODE));
        }
      }
      resultList = new ArrayList<>();
      resultList.add(startDateOptionVO);
      resultList.add(endDateOptionVO);
    } catch (Exception e) {
      logger.error(e.getMessage());
      return ExceptionUtil.getExceptionMsg(e);
    }
    return ServerResponse.createBySuccess(resultList);
  }

  /**
   * 初始化部门
   *
   * @param vbaParamsDTO VBA参数对象
   * @return ServerResponse<VbaReportOptionVO>
   */
//  @Override
//  public ServerResponse<VbaReportOptionVO<DimInfo>> initDept(VbaParamsDTO vbaParamsDTO) {
//
//    VbaReportOptionVO<DimInfo> deptOptionVO;
//    try {
//      AssertUtil.assertNotEmpty(vbaParamsDTO.getProjectId(), ResultCodeEnum.CODE4005.getDisplay());
//      AssertUtil.assertNotEmpty(vbaParamsDTO.getParam(), ResultCodeEnum.CODE4006.getDisplay());
//      ServerResponse<PageInfo<DimInfo>> pageInfoResponse =
//          reportService.initDept(-1, -1, vbaParamsDTO.getProjectId(), vbaParamsDTO.getParam());
//      // 判断是否为真
//      AssertUtil.assertTrue(pageInfoResponse.isSuccess(), pageInfoResponse.getMsg());
//      List<DimInfo> dimInfoList = pageInfoResponse.getData().getList();
//      deptOptionVO = new VbaReportOptionVO<>("defaultReportDept", "默认报告部门下拉框选项", "部门",
//          VbaOptionType.COMBO_BOX.getCode());
//      if (!ObjectUtils.isEmpty(dimInfoList)) {
//        deptOptionVO.setDefaultValue(dimInfoList.get(0).getCode());
//        deptOptionVO.setOptionDictionaryList(dimInfoList);
//      }
//    } catch (Exception e) {
//      logger.error(e.getMessage());
//      return ExceptionUtil.getExceptionMsg(e);
//    }
//
//    return ServerResponse.createBySuccess(deptOptionVO);
//  }

//  @Override
//  public ServerResponse<VbaReportOptionVO<DimInfo>> initCst(VbaParamsDTO vbaParamsDTO) {
//    VbaReportOptionVO<DimInfo> cstOptionVO;
//    try {
//      AssertUtil.assertNotEmpty(vbaParamsDTO.getProjectId(), ResultCodeEnum.CODE4005.getDisplay());
//      AssertUtil.assertNotEmpty(vbaParamsDTO.getParam(), ResultCodeEnum.CODE4006.getDisplay());
//      ServerResponse<PageInfo<DimInfo>> pageInfoResponse =
//          reportService.initCst(-1, -1, vbaParamsDTO.getProjectId(), vbaParamsDTO.getParam());
//      AssertUtil.assertTrue(pageInfoResponse.isSuccess(), pageInfoResponse.getMsg());
//      List<DimInfo> dimInfoList = pageInfoResponse.getData().getList();
//      cstOptionVO = new VbaReportOptionVO<>("defaultReportCst", "默认报告交易对手下拉框选项", "交易对手",
//          VbaOptionType.COMBO_BOX.getCode());
//      if (!ObjectUtils.isEmpty(dimInfoList)) {
//        cstOptionVO.setDefaultValue(dimInfoList.get(0).getCode());
//        cstOptionVO.setOptionDictionaryList(dimInfoList);
//      }
//    } catch (Exception e) {
//      logger.error(e.getMessage());
//      return ExceptionUtil.getExceptionMsg(e);
//    }
//
//    return ServerResponse.createBySuccess(cstOptionVO);
//  }

  /**
   * 初始化组团
   *
   * @param vbaParamsDTO VBA参数对象
   * @return ServerResponse<VbaReportOptionVO>
   */
//  @Override
//  public ServerResponse<VbaReportOptionVO<DimInfo>> initPrj(VbaParamsDTO vbaParamsDTO) {
//
//    VbaReportOptionVO<DimInfo> prjOptionVO;
//    try {
//      AssertUtil.assertNotEmpty(vbaParamsDTO.getProjectId(), ResultCodeEnum.CODE4005.getDisplay());
//      AssertUtil.assertNotEmpty(vbaParamsDTO.getParam(), ResultCodeEnum.CODE4006.getDisplay());
//      ServerResponse<PageInfo<DimInfo>> pageInfoResponse =
//          reportService.initPrj(-1, -1, vbaParamsDTO.getProjectId(), vbaParamsDTO.getParam());
//      AssertUtil.assertTrue(pageInfoResponse.isSuccess(), pageInfoResponse.getMsg());
//      List<DimInfo> dimInfoList = pageInfoResponse.getData().getList();
//      prjOptionVO = new VbaReportOptionVO<>("defaultReportPrj", "默认报告组团下拉框选项", "组团对手",
//          VbaOptionType.COMBO_BOX.getCode());
//      if (!ObjectUtils.isEmpty(dimInfoList)) {
//        prjOptionVO.setDefaultValue(dimInfoList.get(0).getCode());
//        prjOptionVO.setOptionDictionaryList(dimInfoList);
//      }
//    } catch (Exception e) {
//      logger.error(e.getMessage());
//      return ExceptionUtil.getExceptionMsg(e);
//    }
//
//    return ServerResponse.createBySuccess(prjOptionVO);
//  }


  /**
   * 将auditService中获得的开始结束日期转化为需要的格式存储
   *
   * @param reportDates reportDates
   * @return Map
   */
  private Map<String, List<JSONObject>> convertReportDates(List<ReportDate> reportDates) {
    if (reportDates == null) {
      return null;
    }
    List<JSONObject> startDateList = new LinkedList<>();
    List<JSONObject> endDateList = new LinkedList<>();
    // reportDates的结构如下: 介于希望VBA前段日期显示从前到后, 所以反向循环结构
    for (int i = reportDates.size() - 1; i >= 0; i--) {
      ReportDate reportDateObj = reportDates.get(i);
      List<DateInfo> yearDateList = reportDateObj.getReportDates();
      for (DateInfo yearDate : yearDateList) {
        String acgYr = yearDate.getAcgYr();
        String acgMo = yearDate.getAcgMo();
        acgMo = acgMo.length() > 1 ? acgMo : "0" + acgMo;
        JSONObject startDate = new JSONObject();
        JSONObject endDate = new JSONObject();
        String code = acgYr + UNDERLINE_SEPARATOR + acgMo;
        startDate.put(OPTION_CODE, code);
        startDate.put(OPTION_VALUE, yearDate.getSaleDtBgn());
        startDate.put(OPTION_LEVEL, DEFAULT_OPTION_LEVEL);
        endDate.put(OPTION_CODE, code);
        endDate.put(OPTION_VALUE, yearDate.getSaleDtEnd());
        endDate.put(OPTION_LEVEL, DEFAULT_OPTION_LEVEL);
        startDateList.add(startDate);
        endDateList.add(endDate);
      }
    }
    Map<String, List<JSONObject>> startEndDateListMap = new HashMap<>(2);
    startEndDateListMap.put(START_DATE_KEY, startDateList);
    startEndDateListMap.put(END_DATE_KEY, endDateList);
    return startEndDateListMap;
  }

  @Override
  public ServerResponse<ArrayList<Map<String, Object>>> getTimeAccount(VbaParamsDTO vbaParamsDTO) {
    KeyAndValueDTO<String, ArrayList<Map<String, Object>>> result;
    try {
      AssertUtil.assertNotEmpty(vbaParamsDTO.getProjectId(), "项目不能为空");
      AssertUtil.assertNotEmpty(vbaParamsDTO.getYear(), "getYear不能为空");
      AssertUtil.assertNotEmpty(vbaParamsDTO.getMonthBegin(), "getMonthBegin不能为空");
      AssertUtil.assertNotEmpty(vbaParamsDTO.getMonthEnd(), "getMonthEnd不能为空");
      AssertUtil.assertNotEmpty(vbaParamsDTO.getAccBookId(), "getAccBookId不能为空");
      String sqlText = projectRptSqlService.getSqlTextByInfo(vbaParamsDTO.getProjectId(),
          ReportTypeEnum.JOURNAL_VBA.getCode());

      Map<String, Object> conditionMap = new HashMap<>(4);
      conditionMap.put("year", vbaParamsDTO.getYear());
      conditionMap.put("begin_month", vbaParamsDTO.getMonthBegin());
      conditionMap.put("end_month", vbaParamsDTO.getMonthEnd());
      conditionMap.put("actbk_cd", vbaParamsDTO.getAccBookId());
      result = this.interceptData(
          commonExecuteService.queryListByMap(vbaParamsDTO.getProjectId(), sqlText, conditionMap));
    } catch (Exception e) {
      logger.error(e.getMessage());
      return ExceptionUtil.getExceptionMsg(e);
    }
    return ServerResponse.createBySuccess(result.getKey(), result.getValue());
  }


//  @Override
//  public ServerResponse<ArrayList<Map<String, Object>>> queryDefaultReport(
//      ReportCondition reportCondition) {
//    KeyAndValueDTO<String, ArrayList<Map<String, Object>>> result;
//    try {
//      reportCondition.setPageSize(VBA_REPORT_FETCH_LIMITATION);
//      PageInfo<Map<String, Object>> reportDataPage = reportService.getReportData(reportCondition);
//      result = this.interceptData(convertReportData(reportDataPage.getList(), reportCondition));
//    } catch (Exception e) {
//      logger.error(e.getMessage());
//      return ExceptionUtil.getExceptionMsg(e);
//    }
//    return ServerResponse.createBySuccess(result.getKey(), result.getValue());
//  }

  /**
   * 将auditService中得到的默认报表的结果做一次信息转化 1. 将汇总的明细提取出来 2. 添加客户,部门,交易对手,组团信息
   * 
   * @param originalData originalData
   * @param condition condition
   * @return List
   */
  private List<Map<String, Object>> convertReportData(List<Map<String, Object>> originalData,
      ReportCondition condition) {
    for (Map<String, Object> dataMap : originalData) {
      dataMap.put(CORP_CODE, condition.getCorpCd());
      dataMap.put(CORP_NAME, condition.getCorpNm());
      dataMap.put(CST_CODE, condition.getCstCd());
      dataMap.put(DEPT_CODE, condition.getDeptCd());
      dataMap.put(PRJ_CODE, condition.getPrjCd());
    }
    return originalData;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public ServerResponse<VbaReportOptionVO<JSONObject>> queryAllBookSet(VbaParamsDTO vbaParamsDTO) {
    VbaReportOptionVO<JSONObject> optionVO;
    try {
      String sqlText = projectRptSqlService.getSqlTextByInfo(vbaParamsDTO.getProjectId(),
          ReportTypeEnum.ALL_BOOK_SET.getCode());
      // 获取数据库连接
      final List<Map<String, Object>> records =
          commonExecuteService.queryListByString(vbaParamsDTO.getProjectId(), sqlText);
      ArrayList<JSONObject> jsonList = new ArrayList<>();
      for (Map<String, Object> record : records) {
        final JSONObject jsonobject = new JSONObject();
        jsonobject.put(OPTION_CODE, record.get("账套编码"));
        jsonobject.put(OPTION_VALUE, record.get("账套名称"));
        jsonobject.put(OPTION_KEY, record.get("账套主键"));
        jsonList.add(jsonobject);
      }
      optionVO = new VbaReportOptionVO<>("defaultReportCorp", "默认报告客户下拉框选项", "客户",
          VbaOptionType.COMBO_BOX.getCode());
      if (!jsonList.isEmpty()) {
        optionVO.setDefaultValue(jsonList.get(0).getString(OPTION_CODE));
        optionVO.setOptionDictionaryList(jsonList);
      }
    } catch (Exception e) {
      logger.error(e.getMessage());
      return ExceptionUtil.getExceptionMsg(e);
    }

    return ServerResponse.createBySuccess(optionVO);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public ServerResponse<ArrayList<Map<String, Object>>> querySubBalanceAccount(
      VbaParamsDTO vbaParamsDTO) {
    KeyAndValueDTO<String, ArrayList<Map<String, Object>>> result;
    try {

      AssertUtil.assertNotEmpty(vbaParamsDTO.getProjectId(), "项目不能为空");
      AssertUtil.assertNotEmpty(vbaParamsDTO.getYear(), "年度不能为空");
      AssertUtil.assertNotEmpty(vbaParamsDTO.getMonthBegin(), "开始月份不能为空");
      AssertUtil.assertNotEmpty(vbaParamsDTO.getMonthEnd(), "结束月份不能为空");
      AssertUtil.assertNotEmpty(vbaParamsDTO.getAccBookId(), "AccBookId不能为空");
      Map<String, Object> params = new HashMap<>(4);
      params.put("year", vbaParamsDTO.getYear());
      params.put("begin_month", vbaParamsDTO.getMonthBegin());
      params.put("end_month", vbaParamsDTO.getMonthEnd());
      params.put("ACTBK_CD", vbaParamsDTO.getAccBookId());
      String sqlText = projectRptSqlService.getSqlTextByInfo(vbaParamsDTO.getProjectId(),
          ReportTypeEnum.SUBJECT_BALANCE_VBA.getCode());
      List<Map<String, Object>> records =
          commonExecuteService.queryListByMap(vbaParamsDTO.getProjectId(), sqlText, params);
      result = this.interceptData(records);
    } catch (Exception e) {
      logger.error(e.getMessage());
      return ExceptionUtil.getExceptionMsg(e);
    }
    return ServerResponse.createBySuccess(result.getKey(), result.getValue());

  }

  @Override
  @DynamicDS("projectId")
  public ServerResponse<HashMap<String, Object>> getReportDefaultSelections(String projectId,
      String reportId) {
    try {
      Map<String, Object> userHistory = reportMapper.queryUserHistory(reportId);
      HashMap<String, Object> object = new HashMap<>();
      object.put(CORP_CODE, userHistory.get("CORP_CD"));
      object.put(CORP_NAME, userHistory.get("CORP_NM"));
      String start = userHistory.get("SALE_DT_BGN").toString();
      String end = userHistory.get("SALE_DT_END").toString();
      object.put("defaultStartDate",
          start.split("/")[0] + UNDERLINE_SEPARATOR + start.split("/")[1]);
      object.put(START_DATE_KEY, start);
      object.put("defaultEndDate", end.split("/")[0] + UNDERLINE_SEPARATOR + end.split("/")[1]);
      object.put(END_DATE_KEY, end);

      return ServerResponse.createBySuccess(object);
    } catch (Exception e) {
      logger.error(e.getMessage());
      return ExceptionUtil.getExceptionMsg(e);
    }
  }


  /**
   * {@inheritDoc}
   */
  @Override
  public ServerResponse<String> saveOptionData(OptionDataModel optionData) {
    try {
      final String username = optionData.getUsername();
      final String projectId = optionData.getProjectId();
      SysUsr user = ContextHolderUtils.getLoginUser();
      final String userId = username == null ? "" : user.getUsrId();
      // updateUserName属性不为空时，说明是更高权限用户更新
      ArrayList<SysUsrOption> list = new ArrayList<>();
      SysUsrOption data;
      Date currentDate = new Date(System.currentTimeMillis());
      if (optionData.getAccBookOptId() != null && optionData.getAccBookOptId().length() > 0) {
        data = new SysUsrOption(userId, projectId, false, userId, currentDate);
        list.addAll(
            this.setSysUsrOptionProperties(optionData.getAccBookOptId(), optionData.getAccBookId(),
                optionData.getAccBookName(), SysOptionCodeEnum.ACCOUNT_BOOK.getCode(), data));
      } else {
        data = new SysUsrOption(userId, projectId, false, userId, currentDate);
        list.addAll(
            this.setSysUsrOptionProperties(optionData.getCorpOptId(), optionData.getCorpId(),
                optionData.getCorpName(), SysOptionCodeEnum.CORP.getCode(), data));
      }
      data = new SysUsrOption(userId, projectId, false, userId, currentDate);
      list.addAll(
          this.setSysUsrOptionProperties(optionData.getBeginTimeOptId(), optionData.getBeginTime(),
              optionData.getBeginTimeDisplay(), SysOptionCodeEnum.START_DATE.getCode(), data));
      data = new SysUsrOption(userId, projectId, false, userId, currentDate);
      list.addAll(
          this.setSysUsrOptionProperties(optionData.getEndTimeOptId(), optionData.getEndTime(),
              optionData.getEndTimeDisplay(), SysOptionCodeEnum.END_DATE.getCode(), data));
      if (!list.isEmpty()) {
        sysUsrOptionMapper.upOptions(list);
      }
    } catch (Exception e) {
      logger.error(e.getMessage());
      return ExceptionUtil.getExceptionMsg(e);
    }

    return ServerResponse.createBySuccess();
  }

  private List<SysUsrOption> setSysUsrOptionProperties(String optionId, String optionValue,
      String optionName, String optionCode, SysUsrOption data) {
    List<SysUsrOption> list = new ArrayList<>();
    if (optionValue != null && optionId != null) {
      data.setOptionId(optionId);
      data.setOptionCode(optionCode);
      data.setOptionValue(optionValue);
      data.setOptionName(optionName);
      list.add(data);
    }
    return list;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public ServerResponse<ArrayList<SysUsrOption>> queryDefaultOptionData(VbaParamsDTO vbaParamsDTO) {
    ArrayList<SysUsrOption> list;
    try {
      SysUsr user = ContextHolderUtils.getLoginUser();
      AssertUtil.assertNotEmpty(user.getUsrId(), "UserId不能为空");
      AssertUtil.assertNotEmpty(vbaParamsDTO.getProjectId(), "ProjectId不能为空");
      list = sysUsrOptionMapper.selectByUsrIdAndPrjId(user.getUsrId(), vbaParamsDTO.getProjectId());
      if (list.isEmpty()) {
        Date currentDate = new Date(System.currentTimeMillis());
        List<SysOption> sysOptions = sysOptionService.selectList(new EntityWrapper<>());
        for (SysOption item : sysOptions) {
          SysUsrOption option = new SysUsrOption(user.getUsrId(), vbaParamsDTO.getProjectId(),
              false, user.getUsrId(), currentDate, item.getOptionId(), item.getOptionCode());
          list.add(option);
        }
        sysUsrOptionMapper.insertOptionList(list);
      }
    } catch (Exception e) {
      logger.error(e.getMessage());
      return ExceptionUtil.getExceptionMsg(e);
    }
    return ServerResponse.createBySuccess(list);
  }

//  @Override
//  public ServerResponse<ArrayList<Map<String, Object>>> searchReport(
//      ReportCondition reportCondition) {
//    ArrayList<Map<String, Object>> reportData;
//    try {
//      AssertUtil.assertNotEmpty(reportCondition.getProjectId(), "project 不能为空");
//      reportCondition.setPageSize(VBA_REPORT_FETCH_LIMITATION);
//      PageInfo<Map<String, Object>> reportDataPageInfo =
//          reportService.getReportData(reportCondition);
//      reportData = new ArrayList<>(reportDataPageInfo.getList());
//    } catch (Exception e) {
//      logger.error(e.getMessage());
//      return ExceptionUtil.getExceptionMsg(e);
//    }
//    return ServerResponse.createBySuccess(reportData);
//  }


  @Override
  @SuppressWarnings("unchecked")
  public ServerResponse<JSONObject> getChkAccountData(AccountQueryVO accountQueryVO, int num) {

    SysUsr user = ContextHolderUtils.getLoginUser();
    return accountCheckService.getChkAccountData(user.getUsrAcc(), accountQueryVO.getProjectId(),
        accountQueryVO, -1);
  }

  /**
   * 超大数据处理，截取最大数据量
   *
   * @param data 数据信息
   * @param <T> 类型
   * @return KeyAndValueDTO
   */
  private <T> KeyAndValueDTO<String, ArrayList<T>> interceptData(List<T> data) {
    KeyAndValueDTO<String, ArrayList<T>> result = new KeyAndValueDTO<>();
    if (data.size() > VBA_REPORT_FETCH_LIMITATION) {
      result.setKey(String.format("查询结果%d条,超过最大限制%d条", data.size(), VBA_REPORT_FETCH_LIMITATION));
      result.setValue(new ArrayList<>(data.subList(0, VBA_REPORT_FETCH_LIMITATION)));
    } else {
      result.setKey("");
      result.setValue(new ArrayList<>(data));
    }
    return result;
  }

}
